package org.example.springboot3.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.springboot3.entity.Employee;
import org.example.springboot3.exception.CustomException;
import org.example.springboot3.service.EmployeeService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
/**
 * JWT验证器
 */
@Component
// 实现 HandlerInterceptor 接口，表明这是一个 Spring 拦截器
public class JWTInterceptor implements HandlerInterceptor {
 @Resource
 EmployeeService employeeService;
    // 重写 HandlerInterceptor 接口的 preHandle 方法，该方法会在请求处理之前被调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        // 从请求头中获取名为 "token" 的 JWT 令牌
        if (StrUtil.isBlank(token)) {
            //1 检查令牌是否为空
            token = request.getParameter("token");
        }   //2 如果请求头中没有令牌，尝试从请求参数中获取

        if (StrUtil.isBlank(token)) {  // 再次检查令牌是否为空
            throw new CustomException("401", "令牌为空，无权限");
        }
        // 初始化 Employee 对象，用于存储从数据库中查询到的员工信息
        Employee employee = null;
        try {
           //3  解码 JWT 令牌，获取其中的受众信息
            String audience = JWT.decode(token).getAudience().get(0);
            String[] split = audience.split("-");
            String username = split[0];
            String role = split[1];
            //4 根据角色查询员工信息
            if ("adm".equals(role)) {
                employee = employeeService.selectByUsername(username);
            } else if ("EMP".equals(role)) {
                employee = employeeService.selectByUsername(username);
            }
        } catch (Exception e) {
            throw new CustomException("401", "解析令牌或查询员工信息时出现异常，无权限");
        }
            if (employee == null) {
                throw new CustomException("401", "员工信息为空，无权限");
            }
        try{ //5 创建 JWT 验证器，使用员工的密码作为密钥
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(employee.getPassword())).build();
            jwtVerifier.verify(token); // 验证 JWT 令牌的有效性
        } catch (Exception e){
            throw new CustomException("401", " 验证失败，无权限");
        }
        return true;//如果所有验证都通过boolean值：true，允许请求继续处理
    }
}



































//import cn.hutool.core.util.StrUtil;
//
//import com.auth0.jwt.exceptions.JWTVerificationException;
//import jakarta.annotation.Resource;
//import jakarta.servlet.http.HttpServletRequest;
//import jakarta.servlet.http.HttpServletResponse;
//import org.example.springboot3.entity.Employee;
//import org.example.springboot3.exception.CustomException;
//import org.example.springboot3.service.EmployeeService;
//import org.example.springboot3.utils.TokenUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.stereotype.Component;
//import org.springframework.web.servlet.HandlerInterceptor;
//
//@Component
//public class JWTInterceptor implements HandlerInterceptor {
//
//    private static final Logger logger = LoggerFactory.getLogger(JWTInterceptor.class);
//
//    @Resource
//    private EmployeeService employeeService;
//
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String token = request.getHeader("token");
//        if (StrUtil.isBlank(token)) {
//            token = request.getParameter("token");
//        }
//        // 打印获取到的 token
//        System.out.println("获取到的 token: " + token);
//
//
//        if (StrUtil.isBlank(token)) {
//            throw new CustomException("401", "你无权限操作，未提供有效的 token");
//        }
//
//        Employee employee = null;
//        try {
//            String username = TokenUtils.getUsernameFromToken(token);
//            employee = employeeService.selectByName(username);
//        } catch (Exception e) {
//            logger.error("解析 token 或获取 Employee 对象时出错", e);
//            throw new CustomException("401", "解析 token 或获取 Employee 对象时出错，错误信息: " + e.getMessage());
//        }
//
//        if (employee == null) {
//            throw new CustomException("401", "你无权限操作，未找到对应的用户信息");
//        }
//
//        try {
//            if (!TokenUtils.verifyToken(token, employee)) {
//                throw new JWTVerificationException("Token 验证失败");
//            }
//        } catch (JWTVerificationException e) {
//            logger.error("Token 验证失败", e);
//            throw new CustomException("401", "你无权限操作，token 验证失败");
//        }
//        return true;
//    }
//}